package com.erp.order.purchasing.service.impl;

import cn.alibaba.open.param.*;
import com.activiti.dao.model.Activiti_SubTaskInfo;
import com.activiti.dao.model.Activiti_SubTaskInfoRO;
import com.activiti.dao.model.Activiti_TaskInfo;
import com.activiti.dao.service.ActivitiService;
import com.activiti.dao.service.TaskSubService;
import com.alibaba.jingn.service.MaterialService;
import com.erp.hr.base.model.ApprovalVO;
import com.erp.hr.base.service.impl.BaseServiceImpl;
import com.erp.hr.base.util.CommonUtils;
import com.erp.hr.base.vo.LegalityResultVO;
import com.erp.hr.base.vo.ResultVO;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.order.purchasing.dao.InquiryListDao;
import com.erp.order.purchasing.model.*;
import com.erp.order.purchasing.service.*;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.redragon.framework.hibernate.model.Pages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 询价单 业务实现层
 * @Author: syz
 * @blame syz
 * @CreateTime: 2021/4/6
 */
@Service
public class InquiryListServiceImpl extends BaseServiceImpl<InquiryListDao, InquiryList> implements InquiryListService {

    /**
     * 采购订单服务
     */
    @Lazy
    @Autowired
    private PurchaseOrderService purchaseOrderService;

    /**
     * 询价单供应商服务
     */
    @Lazy
    @Autowired
    private InquiryListSupplierService inquiryListSupplierService;

    /**
     * 询价单物资服务
     */
    @Lazy
    @Autowired
    private InquiryListMaterialService inquiryListMaterialService;

    /**
     * 申请详情服务
     */
    @Lazy
    @Autowired
    private PurchasingRequisitionDetailService purchasingRequisitionDetailService;

    /**
     * 流程服务
     */
    @Lazy
    @Autowired
    private ActivitiService activitiService;

    /**
     * 运行时服务
     */
    @Lazy
    @Autowired
    private RuntimeService runtimeService;

    /**
     * 任务服务
     */
    @Lazy
    @Autowired
    private TaskService taskService;

    /**
     * 任务子服务
     */
    @Lazy
    @Autowired
    private TaskSubService taskSubService;

    /**
     * 供应商报价服务
     */
    @Lazy
    @Autowired
    private QuotedPriceService quotedPriceService;

    /**
     * 供应商报价详情服务
     */
    @Lazy
    @Autowired
    private QuotedPriceDetailService quotedPriceDetailService;

    /**
     * 1688服务
     */
    @Lazy
    @Autowired
    private MaterialService materialService;

    /**
     * 职员服务
     */
    @Autowired
    private HrCommonService hrCommonService;


    /**
     * 为单个对象添加完整信息
     * @param inquiryList 需要添加完整信息的对象
     * @return 添加完整信息后的对象
     */
    @Override
    public InquiryList addCompleteData(InquiryList inquiryList) {
        if (StringUtils.isNotEmpty(inquiryList.getQuotationClosingDate())) {
            try {
                inquiryList.setQuotationClosingDate(new SimpleDateFormat(CommonUtils.YEAR_MONTH_DAY_TIME).format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(inquiryList.getQuotationClosingDate())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        List<InquiryListSupplier> inquiryListSuppliers = inquiryListSupplierService.addCompleteData(
                inquiryListSupplierService.getListByInquiryListId(inquiryList.getId()));
        inquiryList.setSupplierList(inquiryListSuppliers);
        inquiryList.setCheckNum(inquiryListSuppliers.size());
        List<InquiryListSupplier> suppliers = getSupplierById(inquiryList.getId());
        inquiryList.setQuoteList(suppliers);
        inquiryList.setMaterialList(inquiryListMaterialService.addCompleteData(
                inquiryListMaterialService.getListByInquiryListId(inquiryList.getId())));
        if (CommonUtils.PROCUREMENT_TYPE_COMPARE.equals(inquiryList.getProcurementType()) && suppliers != null && suppliers.size() != 0) {
            inquiryList.setRespondNum(suppliers.size());
            inquiryList.setAveragePrice(calculatedAverage(suppliers));
            addQuoteDetail(inquiryList);
        } else {
            inquiryList.setRespondNum(0);
            inquiryList.setAveragePrice(new BigDecimal("0"));
        }
        return inquiryList;
    }

    /**
     * 添加报价详情
     * @param inquiryList 询价单对象
     */
    private void addQuoteDetail(InquiryList inquiryList) {
        List<InquiryListSupplier> quoteList = inquiryList.getQuoteList();
        List<InquiryListMaterial> materialList = inquiryList.getMaterialList();
        for (InquiryListMaterial ilm : materialList) {
            List<QuotedPriceDetail> quoteMaterialList = dao.getQuoteMaterialList(inquiryList.getId(), ilm.getId());
            BigDecimal min = quoteMaterialList.get(0).getPrice();
            BigDecimal max = quoteMaterialList.get(quoteMaterialList.size() - 1).getPrice();
            ilm.setMin(min);
            ilm.setMax(max);
            ArrayList<BigDecimal> quoteDetailList = new ArrayList<>(quoteList.size());
            ArrayList<String> taxRateList = new ArrayList<>(quoteList.size());
            for (InquiryListSupplier ils : quoteList) {
                if (ils.getMinNum() == null) {
                    ils.setMinNum(0);
                }
                Iterator<QuotedPriceDetail> iterator = quoteMaterialList.iterator();
                while (iterator.hasNext()) {
                    QuotedPriceDetail next = iterator.next();
                    if (next.getSupplierId().equals(ils.getSupplierId().toString())) {
                        BigDecimal price = next.getPrice();
                        quoteDetailList.add(price);
                        taxRateList.add(next.getTaxRate() + "%");
                        if (price.equals(min)) {
                            ils.setMinNum(ils.getMinNum() + 1);
                        }
                        iterator.remove();
                        break;
                    }
                }
            }
            ilm.setQuoteList(quoteDetailList);
            ilm.setTaxRateList(taxRateList);
        }
    }

    /**
     * 计算报价平均值
     * @param supplierList 询价供应商集合
     * @return 报价平均值
     */
    private BigDecimal calculatedAverage(List<InquiryListSupplier> supplierList) {
        BigDecimal result = new BigDecimal("0");
        for (InquiryListSupplier ils : supplierList) {
            result = result.add(ils.getBidAmount());
        }
        result = result.divide(new BigDecimal("" + supplierList.size()), 2, BigDecimal.ROUND_HALF_UP);
        return result;
    }

    /**
     * 为集合添加完整信息
     * @param list 需要添加完整信息的集合
     * @return 添加完整信息后的集合
     */
    @Override
    public List<InquiryList> addCompleteData(List<InquiryList> list) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            for (InquiryList il : list) {
                if (StringUtils.isEmpty(il.getStatus())) {
                    if (new Date().compareTo(sdf.parse(il.getQuotationClosingDate())) >= 0) {
                        il.setStatus("比价中");
                    } else {
                        il.setStatus("询价中");
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 校验数据合法性
     * @param inquiryList 需要校验的对象
     * @return 校验结果
     */
    @Override
    public LegalityResultVO isLegalityData(InquiryList inquiryList) {
        if (StringUtils.isEmpty(inquiryList.getTitle())) {
            return new LegalityResultVO(true, "标题不能为空!");
        }
        if (StringUtils.isEmpty(inquiryList.getProcurementType())) {
            return new LegalityResultVO(true, "采购类型不能为空!");
        }
        if (StringUtils.isEmpty(inquiryList.getBeginDate())) {
            return new LegalityResultVO(true, "请选择开始交货日期!");
        }
        if (StringUtils.isEmpty(inquiryList.getEndDate())) {
            return new LegalityResultVO(true, "请选择结束交货日期!");
        }
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(CommonUtils.YEAR_MONTH_DAY);
        try {
            if (now.compareTo(sdf.parse(inquiryList.getBeginDate())) >= 0) {
                return new LegalityResultVO(true, "开始交货日期不能早于当前时间!");
            }
            if (sdf.parse(inquiryList.getBeginDate()).compareTo(sdf.parse(inquiryList.getEndDate())) >= 0) {
                return new LegalityResultVO(true, "开始交货日期不能晚于结束交货日期!");
            }
        } catch (ParseException e) {
            return new LegalityResultVO(true, "操作失败!");
        }
        if (inquiryList.getMaterialList().isEmpty()) {
            return new LegalityResultVO(true, "物资信息不能为空!");
        }
        if (CommonUtils.PROCUREMENT_TYPE_ONLY.equals(inquiryList.getProcurementType())) {
            return checkOnly(inquiryList);
        } else {
            return checkCompare(inquiryList);
        }
    }

    /**
     * 检查单一采购数据合法性
     * @param inquiryList 需要校验的对象
     * @return 校验结果
     */
    private LegalityResultVO checkOnly(InquiryList inquiryList) {
        List<InquiryListSupplier> supplierList = inquiryList.getSupplierList();
        if (supplierList.isEmpty()) {
            return new LegalityResultVO(true, "请添加供应商信息!");
        }
        if (supplierList.size() > 1) {
            return new LegalityResultVO(true, "只能选择一家供应商!");
        }
        inquiryList.setInquiryType(null);
        inquiryList.setQuotationClosingDate(null);
        inquiryList.setDay(null);
        inquiryList.setQuoteRequest(null);
        inquiryList.setTradingManner(null);
        inquiryList.setDesignatedSettlementDate(null);
        inquiryList.setSettlementDate(null);
        inquiryList.setPaymentStage(null);
        inquiryList.setPayment(null);
        inquiryList.setInvoiceRequirements(null);
        inquiryList.setCertificationRequirements(null);
        inquiryList.setRemark(null);
        inquiryList.setBookBuilding(null);
        inquiryList.setProcurementPortal(null);
        inquiryList.setPriceComparisonWay(null);
        inquiryList.setContactWay(null);
        inquiryList.setContacts(null);
        inquiryList.setPhone(null);
        inquiryList.setProvince(null);
        inquiryList.setCity(null);
        inquiryList.setCounty(null);
        inquiryList.setAddress(null);
        return new LegalityResultVO(false, null);
    }

    /**
     * 检查询比价数据合法性
     * @param inquiryList 需要校验的对象
     * @return 校验结果
     */
    private LegalityResultVO checkCompare(InquiryList inquiryList) {
        if (StringUtils.isEmpty(inquiryList.getInquiryType())) {
            return new LegalityResultVO(true, "请选择询价类型!");
        }
        List<InquiryListSupplier> supplierList = inquiryList.getSupplierList();
        if (CommonUtils.INQUIRY_TYPE_1688.equals(inquiryList.getInquiryType())) {
            if (StringUtils.isEmpty(inquiryList.getProvince())) {
                return new LegalityResultVO(true, "请选择省!");
            }
            if (StringUtils.isEmpty(inquiryList.getCity())) {
                return new LegalityResultVO(true, "请选择市!");
            }
            if (StringUtils.isEmpty(inquiryList.getCounty())) {
                return new LegalityResultVO(true, "请选择县!");
            }
            if (StringUtils.isEmpty(inquiryList.getAddress())) {
                return new LegalityResultVO(true, "请输入收货地址!");
            }
            supplierList.clear();
        } else {
            inquiryList.setProvince(null);
            inquiryList.setCity(null);
            inquiryList.setCounty(null);
            inquiryList.setAddress(null);
            if (supplierList.isEmpty()) {
                return new LegalityResultVO(true, "请添加供应商信息!");
            }
            if (supplierList.size() < CommonUtils.MIN_SUPPLIER_NUM) {
                return new LegalityResultVO(true, "至少需要添加两家供应商!");
            }
        }
        if (StringUtils.isEmpty(inquiryList.getQuotationClosingDate())) {
            return new LegalityResultVO(true, "请选择报价截止日期!");
        }
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(CommonUtils.YEAR_MONTH_DAY);
        try {
            if (now.compareTo(new SimpleDateFormat(CommonUtils.YEAR_MONTH_DAY_TIME).parse(inquiryList.getQuotationClosingDate())) >= 0) {
                return new LegalityResultVO(true, "报价截止日期不能早于当前时间!");
            }
            if (sdf.parse(inquiryList.getQuotationClosingDate()).compareTo(sdf.parse(inquiryList.getBeginDate())) >= 0) {
                return new LegalityResultVO(true, "报价截止日期不能晚于开始交货日期!");
            }
        } catch (ParseException e) {
            return new LegalityResultVO(true, "操作失败!");
        }
        if (inquiryList.getDay() == null) {
            return new LegalityResultVO(true, "请输入交货期!");
        }
        if (StringUtils.isEmpty(inquiryList.getQuoteRequest())) {
            return new LegalityResultVO(true, "请选择报价要求!");
        }
        if (StringUtils.isEmpty(inquiryList.getTradingManner())) {
            return new LegalityResultVO(true, "请选择交易方式!");
        }
        if (CommonUtils.TRADING_MANNER_PAYMENT_DAYS.equals(inquiryList.getTradingManner())) {
            if (StringUtils.isEmpty(inquiryList.getDesignatedSettlementDate())) {
                return new LegalityResultVO(true, "请选择指定账期结算日!");
            }
            if (CommonUtils.DESIGNATED_SETTLEMENT_DATE_TRUE.equals(inquiryList.getDesignatedSettlementDate())) {
                if (StringUtils.isEmpty(inquiryList.getSettlementDate())) {
                    return new LegalityResultVO(true, "请选择账期结算日!");
                }
            } else {
                inquiryList.setSettlementDate(null);
            }
            inquiryList.setPaymentStage(null);
        } else {
            if (StringUtils.isEmpty(inquiryList.getPaymentStage())) {
                return new LegalityResultVO(true, "请选择阶段支付!");
            }
            inquiryList.setDesignatedSettlementDate(null);
            inquiryList.setSettlementDate(null);
        }
        if (StringUtils.isEmpty(inquiryList.getPayment())) {
            return new LegalityResultVO(true, "请选择支付方式!");
        }
        if (StringUtils.isEmpty(inquiryList.getInvoiceRequirements())) {
            return new LegalityResultVO(true, "请选择发票要求!");
        }
        if (StringUtils.isEmpty(inquiryList.getBookBuilding())) {
            return new LegalityResultVO(true, "请选择询价方式!");
        }
        if (StringUtils.isEmpty(inquiryList.getProcurementPortal())) {
            return new LegalityResultVO(true, "请选择采购门户!");
        }
        if (StringUtils.isEmpty(inquiryList.getPriceComparisonWay())) {
            return new LegalityResultVO(true, "请选择比价方式!");
        }
        if (StringUtils.isEmpty(inquiryList.getContactWay())) {
            return new LegalityResultVO(true, "请选择联系方式!");
        }
        if (StringUtils.isEmpty(inquiryList.getContacts())) {
            return new LegalityResultVO(true, "请输入联系人!");
        }
        if (StringUtils.isEmpty(inquiryList.getPhone())) {
            return new LegalityResultVO(true, "请输入联系电话!");
        }
        if (!inquiryList.getPhone().matches(CommonUtils.PHONE_REGEX)) {
            return new LegalityResultVO(true, "请输入正确的联系电话!");
        }
        return new LegalityResultVO(false, null);
    }

    /**
     * 保存对象
     * @param inquiryList 需要保存的对象
     * @return 保存结果
     */
    @Override
    public boolean save(InquiryList inquiryList) {
        setCode(inquiryList);
        if (CommonUtils.PROCUREMENT_TYPE_ONLY.equals(inquiryList.getProcurementType())) {
            inquiryList.setStatus(CommonUtils.INQUIRY_LIST_STATUS_ANSWER_END);
        }
        if (CommonUtils.INQUIRY_TYPE_1688.equals(inquiryList.getInquiryType())) {
            String orderId = create1688InquiryList(inquiryList);
            if (orderId != null) {
                inquiryList.setOtherId(orderId);
                insertDataObject(inquiryList);
            } else {
                return false;
            }
        } else {
            insertDataObject(inquiryList);
            for (InquiryListSupplier ils : inquiryList.getSupplierList()) {
                ils.setInquiryListId(inquiryList.getId());
                setCreateInfo(ils);
                inquiryListSupplierService.insertDataObject(ils);
            }
        }
        for (InquiryListMaterial ilm : inquiryList.getMaterialList()) {
            ilm.setInquiryListId(inquiryList.getId());
            setCreateInfo(ilm);
            inquiryListMaterialService.insertDataObject(ilm);
            String[] details = ilm.getDetailId().split(",");
            for (String s : details) {
                PurchasingRequisitionDetail prd = purchasingRequisitionDetailService.getDataObject(s);
                prd.setInquiryListMaterialId(ilm.getId());
                purchasingRequisitionDetailService.updateDataObject(prd);
            }
        }
        if (CommonUtils.PROCUREMENT_TYPE_ONLY.equals(inquiryList.getProcurementType())) {
            purchaseOrderService.inquiryListToPurchaseOrder(inquiryList.getId());
        }
        return true;
    }

    /**
     * 发布1688询价
     * @param inquiryList 询价单对象
     * @return 询价单id
     */
    private String create1688InquiryList(InquiryList inquiryList) {
        String username = getStaffInfo().getAccount_id_1688();
        if (username != null) {
            CaigouApiBuyofferPostBuyofferParam cabpbp = new CaigouApiBuyofferPostBuyofferParam();
            cabpbp.setSubject(inquiryList.getTitle());
            cabpbp.setSubUserId(Long.valueOf(username));
            cabpbp.setContact(inquiryList.getContacts());
            cabpbp.setPhone(inquiryList.getPhone());
            cabpbp.setDescription(inquiryList.getRemark());
            try {
                cabpbp.setGmtQuotationExpire(new SimpleDateFormat(CommonUtils.YEAR_MONTH_DAY_TIME).parse(inquiryList.getQuotationClosingDate()));
                cabpbp.setGmtReceiveBeginDate(new SimpleDateFormat(CommonUtils.YEAR_MONTH_DAY).parse(inquiryList.getBeginDate()));
                cabpbp.setGmtReceive(new SimpleDateFormat(CommonUtils.YEAR_MONTH_DAY).parse(inquiryList.getEndDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if ("0".equals(inquiryList.getInvoiceRequirements())) {
                cabpbp.setInvoiceRequirement("vat");
                cabpbp.setInvoiceSubType("self");
            } else if ("1".equals(inquiryList.getInvoiceRequirements())) {
                cabpbp.setInvoiceRequirement("vat");
            } else if ("2".equals(inquiryList.getInvoiceRequirements())) {
                cabpbp.setInvoiceRequirement("ordinary");
            }
            List<String> certificateIds = new ArrayList<>();
            if (inquiryList.getCertificationRequirements().contains("0")) {
                certificateIds.add("1");
            }
            if (inquiryList.getCertificationRequirements().contains("1")) {
                certificateIds.add("2");
            }
            if (inquiryList.getCertificationRequirements().contains("2")) {
                certificateIds.add("3");
            }
            if (!certificateIds.isEmpty()) {
                cabpbp.setCertificateIds(certificateIds);
            }
            cabpbp.setVisibleAfterEndQuote(true);
            if (inquiryList.getQuoteRequest().contains("0")) {
                cabpbp.setIncludeTax(true);
            } else {
                cabpbp.setIncludeTax(false);
            }
            if (inquiryList.getQuoteRequest().contains("1")) {
                cabpbp.setQuoteHasPostFee(true);
            } else {
                cabpbp.setQuoteHasPostFee(false);
            }
            cabpbp.setAllowPartOffer(false);
            cabpbp.setOpen(true);
            if ("0".equals(inquiryList.getProcurementPortal())) {
                cabpbp.setOpenToPortal(true);
            } else {
                cabpbp.setOpenToPortal(false);
            }
            if ("0".equals(inquiryList.getTradingManner())) {
                cabpbp.setProcessTemplateCode("accountPeriod");
                if ("0".equals(inquiryList.getDesignatedSettlementDate())) {
                    cabpbp.setBalanceDateType("notspecify");
                    cabpbp.setBalanceDateValue(getDictByKey("settlement_date").get(inquiryList.getSettlementDate()).replace("天", ""));
                }
                if ("1".equals(inquiryList.getDesignatedSettlementDate())) {
                    cabpbp.setBalanceDateType("specify");
                }
            } else {
                if ("0".equals(inquiryList.getPaymentStage())) {
                    cabpbp.setProcessTemplateCode("stepTrade91BusinessBuy");
                }
                if ("1".equals(inquiryList.getPaymentStage())) {
                    cabpbp.setProcessTemplateCode("stepTrade631BusinessBuy");
                }
                if ("2".equals(inquiryList.getPaymentStage())) {
                    cabpbp.setProcessTemplateCode("stepTrade361BusinessBuy");
                }
                if ("3".equals(inquiryList.getPaymentStage())) {
                    cabpbp.setProcessTemplateCode("stepTrade37BusinessBuy");
                }
            }
            cabpbp.setTransToolType("3");
            cabpbp.setSubBizType("singlepurchase");
//            cabpbp.setSourceMethodType("allmysupplier");
            cabpbp.setSourceMethodType("selectedmysupplier");
            cabpbp.setSupplierMemberIds(
                    new ArrayList<String>() {{
                        add("b2b-2248544159");
                        add("b2b-2249991577");
                        add("b2b-2518110010");
                    }}
            );
            cabpbp.setReceiveAddressProvince(inquiryList.getProvince());
            cabpbp.setReceiveAddressCity(inquiryList.getCity());
            cabpbp.setReceiveAddressCounty(inquiryList.getCounty());
            cabpbp.setReceiveStreetAddress(inquiryList.getAddress());
            cabpbp.setDeliveryPeriod(inquiryList.getDay());
//            cabpbp.setAllmysupplier(true);
//            cabpbp.setSelectedmysupplier(false);
            cabpbp.setAllmysupplier(false);
            cabpbp.setSelectedmysupplier(true);
            if ("0".equals(inquiryList.getContactWay())) {
                cabpbp.setOpenContact2All(true);
            } else if ("1".equals(inquiryList.getContactWay())) {
                cabpbp.setNeedAudit4OpenContact(true);
            } else if ("2".equals(inquiryList.getContactWay())) {
                cabpbp.setOpenContactBeforeQuote(true);
            }
            cabpbp.setSupplierCanModifyQuantity(false);
            List<InquiryListMaterial> materialList = inquiryList.getMaterialList();
            ComAlibabaCaigouCoopapiBuyofferParamPurchaseItemWriteParam[] caccbppiwps = new ComAlibabaCaigouCoopapiBuyofferParamPurchaseItemWriteParam[materialList.size()];
            for (int i = 0; i < materialList.size(); i ++) {
                InquiryListMaterial ilm = materialList.get(i);
                ComAlibabaCaigouCoopapiBuyofferParamPurchaseItemWriteParam caccbppiwp = new ComAlibabaCaigouCoopapiBuyofferParamPurchaseItemWriteParam();
                caccbppiwp.setPurchaseAmount(ilm.getMaterialNumber());
                caccbppiwp.setUnit(ilm.getMaterialUnit());
                caccbppiwp.setProductCode(ilm.getMaterialCode());
                caccbppiwp.setSubject(ilm.getMaterialName());
                caccbppiwp.setBrandName(ilm.getMaterialBrand());
                caccbppiwp.setModelNumber(ilm.getMaterialModel());
                caccbppiwps[i] = caccbppiwp;
            }
            cabpbp.setItems(caccbppiwps);
            Map<String, Object> result = materialService.inquiryparam(cabpbp);
            if((Boolean)result.get(CommonUtils.SUCCESS)) {
                return (String) result.get("orderId");
            }else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 设置询价编号
     * @param inquiryList 需要设置询价编号的对象
     */
    private void setCode(InquiryList inquiryList) {
        StringBuilder sb = new StringBuilder();
        sb.append(CommonUtils.PREFIX_INQUIRY_LIST);
        Calendar calendar = Calendar.getInstance();
        sb.append(calendar.get(Calendar.YEAR));
        sb.append(calendar.get(Calendar.MONTH) + 1);
        sb.append(calendar.get(Calendar.DATE));
        sb.append(getCodeSuffix());
        inquiryList.setCode(sb.toString());
    }

    /**
     * 获取询价编号后缀
     * @return 询价编号后缀
     */
    private String getCodeSuffix() {
        Integer num = dao.getCreateCount() + 1;
        String suffix = num.toString();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < CommonUtils.PURCHASING_REQUISITION_LENGRH - suffix.length(); i ++) {
            result.append("0");
        }
        result.append(suffix);
        return result.toString();
    }

    /**
     * 更新对象
     * @param inquiryList 需要更新的对象
     * @return 更新结果
     */
    @Override
    public boolean update(InquiryList inquiryList) {
        return false;
    }

    /**
     * 根据id删除对象及相关信息
     * @param id 需要删除对象的id
     * @return 删除结果
     */
    @Override
    public boolean linkDelete(Long id) {
        return false;
    }

    @Override
    public List<InquiryListR> getInquiryLists(Pages pages, InquiryListR inquiryListR, String username) {
        return dao.getMdVendorInquiryList(pages,inquiryListR,username);
    }

    /**
     * 根据询价编码获取对象
     * @param code 询价编码
     * @return 询价单对象
     */
    @Override
    public InquiryList getByCode(String code) {
        return dao.getByCode(code);
    }

    /**
     * 获取任务信息
     * @param processInstanceId 流程实例id
     * @return 任务信息集合
     */
    @Override
    public List<Activiti_SubTaskInfoRO> getTaskInfo(String processInstanceId) {
        return taskSubService.getDataObjects(processInstanceId);
    }

    /**
     * 执行审批
     * @param approvalVO 审批vo对象
     * @return 审批结果
     */
    @Override
    public ResultVO<String> approval(ApprovalVO approvalVO) {
        String status;
        InquiryList inquiryList = dao.getByCode(approvalVO.getDataCode());
        Task task = taskService.createTaskQuery().taskId(approvalVO.getTaskId()).singleResult();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(approvalVO.getProcessInstanceId()).singleResult();
        activitiService.erpCompletTask(approvalVO.getTaskId(), approvalVO.getResult(),null);
        if(runtimeService.createProcessInstanceQuery().processInstanceId(approvalVO.getProcessInstanceId()).singleResult() == null) {
            if (CommonUtils.PASS.equals(approvalVO.getResult())) {
                inquiryList.setStatus(CommonUtils.INQUIRY_LIST_STATUS_APPROVAL_END);
                purchaseOrderService.inquiryListToPurchaseOrder(inquiryList.getId());
            } else {
                inquiryList.setStatus(CommonUtils.INQUIRY_LIST_STATUS_APPROVAL_REJECT);
            }
            setUpdateInfo(inquiryList);
            updateDataObject(inquiryList);
            status = CommonUtils.APPROVAL_STATUS_END;
        } else {
            if(CommonUtils.REJECT.equals(approvalVO.getResult())){
                status = CommonUtils.APPROVAL_STATUS_REJECT;
                inquiryList.setStatus(CommonUtils.INQUIRY_LIST_STATUS_APPROVAL_REJECT);
                setUpdateInfo(inquiryList);
                updateDataObject(inquiryList);
            }else{
                status = CommonUtils.APPROVAL_STATUS_UNDERWAY;
            }
        }
        saveSubActivitiTaskInfo(getStaffInfo(), task, processInstance, status, approvalVO.getResult(), approvalVO.getContent());
        return ResultVO.success();
    }

    @Override
    public InquiryList getDataById(int id) {
        return dao.getDataById(id);
    }

    @Override
    public List<InquiryListRS> getQuotedLists(Pages pages, InquiryListRS inquiryListR, String username) {
        return dao.getQuotedLists(pages,inquiryListR,username);
    }

    /**
     * 根据询价单id获取已报价供应商集合
     * @param id 询价单id
     * @return 已报价供应商集合
     */
    @Override
    public List<InquiryListSupplier> getSupplierById(Long id) {
        return dao.getSupplierById(id);
    }

    /**
     * 比价
     * @param priceParityVO 比价vo对象
     * @return 比价结果
     */
    @Override
    public ResultVO<String> priceParity(PriceParityVO priceParityVO) {
        BigDecimal money = new BigDecimal("0");
        InquiryList inquiryList = dao.getDataObject(priceParityVO.getId().toString());
        List<PriceParityDetailVO> sub = priceParityVO.getSub();
        for (PriceParityDetailVO ppd : sub) {
            InquiryListMaterial inquiryListMaterial = inquiryListMaterialService.getDataObject(ppd.getId().toString());
            BigDecimal totalPrice = ppd.getPrice().multiply(new BigDecimal("" + inquiryListMaterial.getMaterialNumber()));
            inquiryListMaterial.setSupplierId(ppd.getSupplierId());
            inquiryListMaterial.setPrice(ppd.getPrice());
            inquiryListMaterial.setTotalPrice(totalPrice);
            inquiryListMaterialService.updateDataObject(inquiryListMaterial);
            money = money.add(totalPrice);
        }
        inquiryList.setMoney(money);
        inquiryList.setStatus(CommonUtils.INQUIRY_LIST_STATUS_APPROVAL);
        HrStaffInfoRO staffInfo = getStaffInfo();
        String id;
        String key;
        Map<String, Object> param = new HashMap<>(3);
        if (isHeadOffice(staffInfo.getCompanyCode())) {
            id = CommonUtils.HEAD_OFFICE_PRICE_PARITY_ID;
            key = CommonUtils.HEAD_OFFICE_PRICE_PARITY_KEY;
            param.put("cgy_id", staffInfo.getStaffCode());
            param.put("bmfzr_id_list", getCodeSetByDepartmentCode(
                    new HashSet<String>() {{
                        add(staffInfo.getDepartmentCode());
                    }},
                    CommonUtils.BMFZR));
        } else {
            id = CommonUtils.FILIALE_PRICE_PARITY_ID;
            key = CommonUtils.FILIALE_PRICE_PARITY_KEY;
            param.put("cgy_id", staffInfo.getStaffCode());
            param.put("xmjl_id_list", getCodeSetByDepartmentCode(
                    new HashSet<String>() {{
                        add(staffInfo.getDepartmentCode());
                    }},
                    CommonUtils.XMFZR));
            param.put("fgsld_id_list", getCodeSetByCompanyCode(
                    new HashSet<String>() {{
                        add(staffInfo.getCompanyCode());
                    }},
                    CommonUtils.FGSFZR));
        }
        ProcessInstance processInstance = activitiService.erpStartProcessInstance(
                key,
                "web/approval/toPriceParityApproval?code=" + inquiryList.getCode(),
                param,
                id);
        Task task = activitiService.erpFindPersonalTaskByPid(processInstance.getProcessInstanceId());
        activitiService.erpCompletTask(
                task.getId(),
                null,
                null);
        saveActivitiTaskInfo(
                inquiryList.getCode() + "(比价结果签批)",
                staffInfo,
                task,
                processInstance,
                "1");
        saveSubActivitiTaskInfo(
                staffInfo,
                task,
                processInstance,
                "1",
                "1",
                staffInfo.getStaffName() + "发起比价结果签批");
        inquiryList.setProcessInstanceId(processInstance.getProcessInstanceId());
        setUpdateInfo(inquiryList);
        dao.updateDataObject(inquiryList);
        return ResultVO.success();
    }

    /**
     * 获取1688比价单
     * @param purchaseId 1688询价单id
     * @param id 1688比价单id
     */
    @Override
    public void getPriceParity(String purchaseId, String id) {
        Map<String,Object> map = materialService.detailsParam(id);
        if(0 == (int) map.get("msg")) {
            if ((boolean) map.get("success")) {
                parsePriceParity(((ComAlibabaCaigouCoopapiPricingchartServicePricingChartCoopServiceGetPricingChartByIdResult) map.get("result")).getData(), purchaseId);
            }
        }
    }

    /**
     * 解析1688比价单
     * @param accpmpccm 比价单详情
     * @param purchaseId 询价单id
     */
    private void parsePriceParity(AlibabaCaigouCoopapiPricingchartModelPricingChartCoopModel accpmpccm, String purchaseId) {
        int num = 0;
        BigDecimal totalPrice = new BigDecimal("0");
        Map<Long, Integer> numMap = new HashMap<>(accpmpccm.getPurchaseItemVOList().length);
        Map<Long, List<Object>> priceMap = new HashMap<>(accpmpccm.getPurchaseItemVOList().length);
        for (AlibabaCaigouCoopapiPricingchartModelPricingChartPurchaseItemModel material1688 : accpmpccm.getPurchaseItemVOList()) {
            numMap.put(material1688.getId(), 0);
        }
        for (AlibabaCaigouCoopapiPricingchartModelPricingChartItemModel supplier1688 : accpmpccm.getPricingChartItemList()) {
            String[] checkedList = supplier1688.getCheckItemIdList();
            if (checkedList != null) {
                num += checkedList.length;
                for (String s : checkedList) {
                    String[] split = s.split(":");
                    for (AlibabaCaigouCoopapiPricingchartModelPricingQuotationItemModel quote1688 : supplier1688.getQuotationItems()) {
                        if (split[0].equals(quote1688.getId().toString())) {
                            numMap.put(quote1688.getPurchaseItemId(), (numMap.get(quote1688.getPurchaseItemId()) + Integer.valueOf(split[1])));
                            priceMap.put(quote1688.getPurchaseItemId(), new ArrayList<Object>(4) {{
                                add(supplier1688.getId());
                                add(quote1688.getPriceNew());
                                add(quote1688.getPriceNew().multiply(new BigDecimal(split[1])));
                            }});
                            totalPrice = totalPrice.add(quote1688.getPriceNew().multiply(new BigDecimal(split[1])));
                            break;
                        }
                    }
                }
            }
        }
        InquiryList inquiryList = dao.getBy1688Id(purchaseId);
        for (AlibabaCaigouCoopapiPricingchartModelPricingChartPurchaseItemModel material1688 : accpmpccm.getPurchaseItemVOList()) {
            if (!material1688.getPurchaseAmount().equals(new BigDecimal(numMap.get(material1688.getId()) + ""))) {
                updateErrorInquiryList(inquiryList);
                return;
            }
        }
        if (num != accpmpccm.getPurchaseItemVOList().length) {
            updateErrorInquiryList(inquiryList);
            return;
        }
        String user = inquiryList.getCreateUser();
        Date now = new Date();
        List<InquiryListMaterial> inquiryListMaterialList = inquiryListMaterialService.getListByInquiryListId(inquiryList.getId());
        for (InquiryListMaterial ilm : inquiryListMaterialList) {
            for (AlibabaCaigouCoopapiPricingchartModelPricingChartPurchaseItemModel material1688 : accpmpccm.getPurchaseItemVOList()) {
                if (ilm.getMaterialCode().equals(material1688.getProductCode())) {
                    List<Object> info = priceMap.get(material1688.getId());
                    info.add(ilm.getId());
                    ilm.setSupplierId(Long.valueOf(info.get(0).toString()));
                    ilm.setPrice(new BigDecimal(info.get(1).toString()));
                    ilm.setTotalPrice(new BigDecimal(info.get(2).toString()));
                    ilm.setUpdateTime(now);
                    inquiryListMaterialService.updateDataObject(ilm);
                    break;
                }
            }
        }
        for (AlibabaCaigouCoopapiPricingchartModelPricingChartItemModel supplier1688 : accpmpccm.getPricingChartItemList()) {
            Long supplierId = supplier1688.getId();
            InquiryListSupplier ils = new InquiryListSupplier();
            ils.setInquiryListId(inquiryList.getId());
            ils.setSupplierId(supplierId);
            ils.setCompany("1688");
            ils.setName(supplier1688.getCompanyName());
            ils.setType(null);
            ils.setTel(null);
            ils.setAddress(supplier1688.getSupplierCompanyAddress());
            ils.setRegisteCapital(supplier1688.getSupplierRegisteredCapital());
            ils.setBidAmount(supplier1688.getTotalPriceNew());
            ils.setIsDel(CommonUtils.IS_DEL_NO);
            ils.setCreateUser(user);
            ils.setCreateTime(now);
            ils.setUpdateUser(user);
            ils.setUpdateTime(now);
            inquiryListSupplierService.insertDataObject(ils);
            QuotedPrice quotedPrice = new QuotedPrice();
            quotedPrice.setInquiryListId(inquiryList.getId().toString());
            quotedPrice.setVendorId(supplierId.toString());
            quotedPrice.setIsDel(CommonUtils.IS_DEL_NO);
            quotedPrice.setCreateUser(user);
            quotedPrice.setCreateTime(now);
            quotedPrice.setUpdateUser(user);
            quotedPrice.setUpdateTime(now);
            quotedPriceService.insertDataObject(quotedPrice);
            for (AlibabaCaigouCoopapiPricingchartModelPricingQuotationItemModel quote1688 : supplier1688.getQuotationItems()) {
                QuotedPriceDetail quotedPriceDetail = new QuotedPriceDetail();
                quotedPriceDetail.setInquiryListId(inquiryList.getId().toString());
                quotedPriceDetail.setSupplierId(supplierId.toString());
                quotedPriceDetail.setMaterialId(priceMap.get(quote1688.getPurchaseItemId()).get(3).toString());
                quotedPriceDetail.setTotal(quote1688.getTotalPriceNew());
                quotedPriceDetail.setPrice(quote1688.getPriceNew());
                quotedPriceDetail.setIsDel(CommonUtils.IS_DEL_NO);
                quotedPriceDetail.setCreateUser(user);
                quotedPriceDetail.setCreateTime(now);
                quotedPriceDetail.setUpdateUser(user);
                quotedPriceDetail.setUpdateTime(now);
                quotedPriceDetailService.insertDataObject(quotedPriceDetail);
            }
        }
        inquiryList.setMoney(totalPrice);
        inquiryList.setStatus(CommonUtils.INQUIRY_LIST_STATUS_APPROVAL);
        HrStaffInfoRO staffInfo = hrCommonService.getStaffInfo(user);
        String id;
        String key;
        Map<String, Object> param = new HashMap<>(3);
        if (isHeadOffice(staffInfo.getCompanyCode())) {
            id = CommonUtils.HEAD_OFFICE_PRICE_PARITY_ID;
            key = CommonUtils.HEAD_OFFICE_PRICE_PARITY_KEY;
            param.put("cgy_id", staffInfo.getStaffCode());
            param.put("bmfzr_id_list", getCodeSetByDepartmentCode(
                    new HashSet<String>() {{
                        add(staffInfo.getDepartmentCode());
                    }},
                    CommonUtils.BMFZR));
        } else {
            id = CommonUtils.FILIALE_PRICE_PARITY_ID;
            key = CommonUtils.FILIALE_PRICE_PARITY_KEY;
            param.put("cgy_id", staffInfo.getStaffCode());
            param.put("xmjl_id_list", getCodeSetByDepartmentCode(
                    new HashSet<String>() {{
                        add(staffInfo.getDepartmentCode());
                    }},
                    CommonUtils.XMFZR));
            param.put("fgsld_id_list", getCodeSetByCompanyCode(
                    new HashSet<String>() {{
                        add(staffInfo.getCompanyCode());
                    }},
                    CommonUtils.FGSFZR));
        }
        ProcessInstance processInstance = activitiService.erpStartProcessInstance(
                key,
                "web/approval/toPriceParityApproval?code=" + inquiryList.getCode(),
                param,
                id);
        Task task = activitiService.erpFindPersonalTaskByPid(processInstance.getProcessInstanceId());
        activitiService.erpCompletTask(
                task.getId(),
                null,
                null);
        saveActivitiTaskInfo(
                inquiryList.getCode() + "(比价结果签批)",
                staffInfo,
                task,
                processInstance,
                "1");
        saveSubActivitiTaskInfo(
                staffInfo,
                task,
                processInstance,
                "1",
                "1",
                staffInfo.getStaffName() + "发起比价结果签批");
        inquiryList.setProcessInstanceId(processInstance.getProcessInstanceId());
        inquiryList.setUpdateTime(now);
        dao.updateDataObject(inquiryList);
    }

    /**
     * 将询价单变更为异常询价单
     * @param inquiryList 需要变更的询价单
     */
    private void updateErrorInquiryList(InquiryList inquiryList){
        inquiryList.setStatus(CommonUtils.INQUIRY_LIST_STATUS_APPROVAL_ERROR);
        inquiryList.setUpdateTime(new Date());
        dao.updateDataObject(inquiryList);
    }

    /**
     * 保存流程任务信息
     * @param bussname 任务名称
     * @param staffInfo 操作人信息
     * @param task 任务信息
     * @param processInstance 进程实例
     * @param status 状态
     */
    private void saveActivitiTaskInfo(String bussname, HrStaffInfoRO staffInfo, Task task, ProcessInstance processInstance, String status) {
        Activiti_TaskInfo activitiTaskInfo = new Activiti_TaskInfo();
        activitiTaskInfo.setCompany_code(staffInfo.getCompanyCode());
        activitiTaskInfo.setTask_id(Integer.parseInt(task.getId()));
        activitiTaskInfo.setDepartment_code(staffInfo.getDepartmentCode());
        activitiTaskInfo.setProc_name(bussname);
        activitiTaskInfo.setProc_inst_id(processInstance.getProcessInstanceId());
        activitiTaskInfo.setStaff_code(staffInfo.getStaffCode());
        activitiTaskInfo.setStatus(status);
        activitiTaskInfo.setCreate_time(new Date());
        activitiService.insertOrUpdateDataObject(activitiTaskInfo);
    }

    /**
     * 保存流程任务详情信息
     * @param staffInfo 操作人信息
     * @param task 任务信息
     * @param processInstance 进程实例
     * @param status 状态
     * @param subStatus 详情状态
     * @param subcontent 内容
     */
    private void saveSubActivitiTaskInfo(HrStaffInfoRO staffInfo, Task task, ProcessInstance processInstance, String status, String subStatus, String subcontent) {
        Activiti_TaskInfo activitiTaskInfo = activitiService.queryActivitiTaskInfoByPid(processInstance.getProcessInstanceId());
        activitiTaskInfo.setStatus(status);
        activitiService.updateDataObject(activitiTaskInfo);
        Activiti_SubTaskInfo activitiSubTaskInfo = new Activiti_SubTaskInfo();
        activitiSubTaskInfo.setTask_id(Integer.parseInt(processInstance.getProcessInstanceId()));
        activitiSubTaskInfo.setCompany_code(staffInfo.getCompanyCode());
        activitiSubTaskInfo.setCreate_time(new Date());
        activitiSubTaskInfo.setTask_sub_id(Integer.parseInt(task.getId()));
        activitiSubTaskInfo.setTask_sub_name(task.getName());
        activitiSubTaskInfo.setDepartment_code(staffInfo.getDepartmentCode());
        activitiSubTaskInfo.setStatus(subStatus);
        activitiSubTaskInfo.setProc_contents(subcontent);
        activitiSubTaskInfo.setStaff_code(staffInfo.getStaffCode());
        activitiSubTaskInfo.setProc_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        taskSubService.insertOrUpdateDataObject(activitiSubTaskInfo);
    }

    @Override
    public List<QuotePriceInfo> getPriceInfoById(Long id) {
        return dao.getPriceInfoById(id);
    }

}